package cn.hdu.goods.category.dao;

import cn.hdu.goods.category.domain.Category;
import cn.itcast.commons.CommonUtils;
import cn.itcast.jdbc.TxQueryRunner;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.MapListHandler;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 分类持久层
 * @author qdmmy6
 *
 */
public class CategoryDao {
    private QueryRunner qr = new TxQueryRunner();

    private Category toCategory(Map<String, Object> map) {
        Category category = CommonUtils.toBean(map, Category.class);
        String pid = (String) map.get("pid");
        if (pid != null) {
            Category parent = new Category();
            parent.setCid(pid);
            category.setParent(parent);
        }
        return category;
    }

    private List<Category> toCategoryList(List<Map<String, Object>> mapList) {
        List<Category> categoryList = new ArrayList<>();
        for (Map<String, Object> map : mapList) {
            Category c = toCategory(map);
            categoryList.add(c);
        }
        return categoryList;
    }

    public List<Category> findAll() throws SQLException {
        /**
         * 1.查询所有一级分类
         */
        String sql = "select * from t_category WHERE pid is NULL";
        List<Map<String, Object>> mapList = qr.query(sql, new MapListHandler());

        List<Category> parents = toCategoryList(mapList);
        for (Category parent : parents) {
            List<Category> children = findByParent(parent.getCid());
            parent.setChildren(children);
        }

        return parents;
    }

    public List<Category> findByParent(String pid) throws SQLException {
        String sql = "SELECT * FROM t_category WHERE pid=?";
        List<Map<String,Object>> mapList = qr.query(sql, new MapListHandler(),pid);
        return toCategoryList(mapList);
    }

}
